package com.littleu.yojoincn.logic.reserve;

import com.littleu.yojoincn.common.exception.http.ParameterException;
import com.littleu.yojoincn.dto.reserve.ReserveCreateDeliveryDTO;
import com.littleu.yojoincn.dto.reserve.ReserveDeliveryItemDTO;
import com.littleu.yojoincn.model.ReserveDO;

import java.math.BigDecimal;
import java.util.List;

public class DeliveryChecker {
    private ReserveCreateDeliveryDTO reserveCreateDeliveryDTO;
    private List<ReserveDeliveryItemDTO> reserveDeliveryItemDOList;
    private BigDecimal serverTotalPrice;
    private ReserveDO reserveDO;

    public DeliveryChecker(ReserveCreateDeliveryDTO dto, ReserveDO reserveDO) {
        this.reserveCreateDeliveryDTO = dto;
        this.reserveDeliveryItemDOList = dto.getSkuList();
        this.reserveDO = reserveDO;
    }

    public void isOK() {
        BigDecimal serverTotalPrice = new BigDecimal("0");
        for (ReserveDeliveryItemDTO reserveDeliveryItemDTO : this.reserveDeliveryItemDOList) {
            serverTotalPrice = serverTotalPrice.add(this.calculateSkuOrderPrice(reserveDeliveryItemDTO));
        }
        this.serverTotalPrice = serverTotalPrice;
        this.totalPriceIsOK(this.reserveDO.getVirtualBalance(), serverTotalPrice);
    }

    private BigDecimal calculateSkuOrderPrice(ReserveDeliveryItemDTO reserveDeliveryItemDTO){
        return reserveDeliveryItemDTO.getPrice().multiply(new BigDecimal(reserveDeliveryItemDTO.getQuantity()));
    }

    private void totalPriceIsOK(BigDecimal reserveBalance, BigDecimal deliveryTotalPrice){
        if((reserveBalance.subtract(deliveryTotalPrice)).compareTo(BigDecimal.ZERO) < 0){
            throw new ParameterException(50012);
        }
    }

    public Integer getTotalCount(){
        return this.reserveCreateDeliveryDTO.getSkuList()
                .stream()
                .map(ReserveDeliveryItemDTO::getQuantity)
                .reduce(Integer::sum)
                .orElse(0);
    }

    public ReserveDO getReserveDO(){
        return this.reserveDO;
    }

    public BigDecimal getServerTotalPrice(){
        return this.serverTotalPrice;
    }
}
